﻿using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Concurrent;
using System.IO;
using System.Linq;

namespace FileLog
{
    //[UnsupportedOSPlatform("browser")]
    [ProviderAlias("ColorConsole")]
    public class FileLoggerLoggerProvider : ILoggerProvider
    {
        private readonly ConcurrentDictionary<string, ILogger> _dicLogs=new ConcurrentDictionary<string, ILogger>();
        private readonly IConfiguration _configuration;
        private readonly FileLogOptins _fileOptions;
        private readonly FileLoggingProcessor _fileLoggingProcessor;
        public FileLoggerLoggerProvider
            (
            IConfiguration configuration,
            FileLogOptins options ,
            FileLoggingProcessor fileLoggingProcessor
            )
        {
            
            _fileOptions = options;
            _configuration = configuration;
            _fileLoggingProcessor = fileLoggingProcessor;
        }
        private string GetCategoryName(string categoryName)
        {
            var spaceArr = categoryName.Split('.');
            if (spaceArr.Length == 1) return categoryName;
            var result = string.Join(".", spaceArr.Take(2));
            return result;
        }
        public ILogger CreateLogger(string categoryName)
        {
            var categoryNameKey = GetCategoryName(categoryName);
            var logLevel = _configuration[$"Logging:LogLevel:{categoryNameKey}"]?? _configuration[$"Logging:LogLevel:Default"];
            Enum.TryParse(logLevel,true,out LogLevel level);
            return _dicLogs.GetOrAdd(categoryNameKey, new FileLogger(categoryName, level,_fileOptions, _fileLoggingProcessor));
        }

        public void Dispose()
        {
            _fileLoggingProcessor.Dispose();
        }
    }
}
